import json


class Jsoner(object):
    def __init__(self, item=None):
        """调用时类初始化 同时先执行函数下的代码"""

        self.item = item

    def serialize(self, file_path, rel_path):
        """序列化 将数据成json格式 写入文件"""
        from core.sysuser import split_path

        abs_path = split_path(rel_path, file_path)
        if abs_path == 0:
            return 0
        # 将数据写入<json>文件，<mode=w>先清空文件后写入
        with open(abs_path, "w", encoding='utf-8') as write:
            json.dump(self.item, write, ensure_ascii=False, indent=4)
            return 1

    @staticmethod
    def deserialize(file_path, rel_path):
        """反序列化 将json文件中的数据转换成<dict>类型的数据 并赋值获取"""
        from core.sysuser import split_path

        abs_path = split_path(rel_path, file_path)
        if abs_path == 0:
            return 0
        # 获取<json>文件中的数据
        with open(abs_path, "r", encoding='utf-8') as reader:
            # TODO 必须要设置变量进行参数传递，不然json.load()报错
            text = reader.read()
            if len(text) == 0:
                return {}
            return json.loads(text)


if __name__ == "__main__":
    print(f'\nCurrent File :\n\t<{__file__}>')
